package chapter1;

public class Interpeter 
{
	public static void main(String [] args)
	{	
		String [] ram = {"456","789","234","453", "125", "175", "183", "256","012","100", "000"};
		int [] register = new int[10];
		
		System.out.println(interpeter(register, ram));
	}
	
	public static int interpeter(int [] registers, String [] ram)
	{
		int instructionCount = 0;
		
		for (int index = 0; index < ram.length; index++)
		{
			String instruction = ram[index];
			int firstValue = Integer.parseInt(instruction.substring(0,1));
			int secondValue = Integer.parseInt(instruction.substring(1, 2));
			int thirdValue = Integer.parseInt(instruction.substring(2,3));
			
			switch(firstValue) 
			{
				case 1: // Halt
					if (secondValue == 0 && thirdValue == 0)
					{
						instructionCount++;
						break;
					}
				case 2: // Set register d to n.
					registers[secondValue] = thirdValue;
					instructionCount++;
					continue;
				case 3: // Add n to register d.
					registers[secondValue] += thirdValue;
					instructionCount++;
					continue;
				case 4: // Multiply register d by n.
					registers[secondValue] *= thirdValue;
					instructionCount++;
					continue;
				case 5: // Set register d to value of register s.
					registers[secondValue] = registers[thirdValue];
					instructionCount++;
					continue;
				case 6: // Add value of register s to register d.
					registers[secondValue] += registers[thirdValue];
					instructionCount++;
					continue;
				case 7: // Multiply register d by value of register s.
					registers[secondValue] *= registers[thirdValue];
					instructionCount++;
					continue;
				case 8: // set register d to the value in RAM whose address is in register a
					registers[secondValue] = Integer.parseInt(ram[thirdValue]);
					instructionCount++;
					continue;
				case 9: // set the value in RAM whose address is in register a to the value of register s
					ram[thirdValue] = "" + registers[secondValue];
					instructionCount++;
					continue;
				case 0: // goto the location in register d unless register s contains 0.
					if (thirdValue != 0)
					{
						instructionCount++;
					}
					continue;
			}
		}
		return instructionCount;
	}
}
